package com.cndw.kungfu.model.pve;

import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import com.cndw.kungfu.ext.LogUtil;
import com.cndw.kungfu.ext.TimeProcesser;
import com.cndw.kungfu.model.DataSerialize;

public class UnionPetBattle implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5615580343486210152L;

	/**
	 * 帮派神兽最后开启时间
	 */
	private int openTime;
	/**
	 * 帮派神兽最后一击玩家id集合
	 */
	private Map<Integer, Long> lastAkPlayer = new ConcurrentHashMap<Integer, Long>();
	/**
	 * 当天开启了神兽挑战的帮派Id列表
	 */
	private Set<Integer> openedSet = new HashSet<Integer>();
	/**
	 * 击杀排行
	 */
	private static Map<Integer, List<Object[]>> akOrderMap = new ConcurrentHashMap<Integer, List<Object[]>>(); 
	
	private static Map<Integer, UnionPet> unionPetMap = new ConcurrentHashMap<Integer, UnionPet>();
	
	public static UnionPetBattle getInstance() {
		return DataSerialize.getInstance().getUnionPetBattle();
	}
	
	public void openChallenge(int unionId, int type) {
		if (openedSet.contains(unionId) || unionPetMap.containsKey(unionId)) {
			return;
		}
		openedSet.add(unionId);
		unionPetMap.put(unionId, new UnionPet(unionId, type));
	}

	public boolean isOpened(int unionId) {
		if (openTime < TimeProcesser.getMorningTime()) {
			synchronized (openedSet) {
				if (openTime < TimeProcesser.getMorningTime()) {
					openedSet.clear();
					unionPetMap.clear();
					openTime = TimeProcesser.getMorningTime();
					LogUtil.getMain().info("union pet today init ... ");
					commitSync();
				}
			}
		}
		return openedSet.contains(unionId);
	}
	
	public void removePlayer(int unionId, long playerId) {
		if (unionPetMap.containsKey(unionId)) {
			unionPetMap.get(unionId).removePlayer(playerId);
		}
		
	}
	
	public int getLastOpenTime() {
		return openTime;
	}
	
	public void setLastAk(int unionId, long playerId) {
		lastAkPlayer.put(unionId, playerId);
	}
	
	public void addAkOrder(int unionId, List<Object[]> data) {
		akOrderMap.put(unionId, data);
	}
	
	public List<Object[]> getUnionAkRanking(int unionId) {
		return akOrderMap.get(unionId);
	}

	public UnionPet getUnionPet(int unionId) {
		return unionPetMap.get(unionId);
	}
	
	public void remove(int unionId) {
		unionPetMap.remove(unionId);
	}

	public long getLastAkPlayer(int unionId) {
		if (lastAkPlayer.containsKey(unionId)) {
			return lastAkPlayer.get(unionId);
		}
		return 0;
	}
	
	public void addLastAkPlayer(int unionId, long playerId) {
		lastAkPlayer.put(unionId, playerId);
	}

	public Map<Integer, List<Object[]>> getAkOrderMap() {
		return akOrderMap;
	}
	
	public void commitSync() {
		DataSerialize.getInstance().commitSync();
	}
}
